package com.hk.commons.poi.excel.read.sax.v03.handler;

import com.hk.commons.poi.excel.read.sax.v03.XlsReadContext;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.Record;

import java.util.Objects;

/**
 * 读取到 一个文件的开始,表示sheet或workbook的开始
 *
 * @author Kevin
 */
public class BOFRecordHandler implements XlsRecordHandler {

    private int currentSheetIndex = -1;

    @Override
    public boolean support(Record poiRecord, XlsReadContext readContext) {
        if (poiRecord instanceof BOFRecord bofRecord) {
            var isSheet = bofRecord.getType() == BOFRecord.TYPE_WORKSHEET;
            readContext.setSheet(isSheet);
            return isSheet;//这里只支持读取到为sheet时，才会调用 processRecord() 就去
        }
        return false;
    }

    @Override
    public void processRecord(Record poiRecord, XlsReadContext readContext) {
        currentSheetIndex++;
        if (Objects.isNull(readContext.getStubWorkbook())) {
            readContext.setStubWorkbook(readContext.getWorkbookBuildingListener().getStubHSSFWorkbook());
        }
        if (Objects.isNull(readContext.getOrderBoundSheetRecords())) {
            readContext.setOrderBoundSheetRecords(BoundSheetRecord.orderByBofPosition(readContext.getBoundSheetRecords()));
        }
        readContext.setCurrentSheetIndex(currentSheetIndex);
        readContext.setCurrentSheetName(readContext.getOrderBoundSheetRecords()[currentSheetIndex].getSheetname());
    }
}
